﻿using SSEC.DataBaseDict;
using System;
using System.Collections.Generic;
using System.Data.OracleClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Xiaov.SmartWeb.Model.ActiveRecord;
using Xiaov.SmartWeb.Infrastructure.ExtMethod;
using Xiaov.SmartWeb.Infrastructure.Cache;
using Xiaov.SmartWeb.Model.Statistical.Select;
using System.Web;

namespace Xiaov.SmartWeb.Model.Statistical
{
  /// <summary>
  /// 报表属性
  /// </summary>
  public class BaseReport
  {
    public GridConfig Config { get; set; }

    public S_PM_USER ViewUser { get; set; }

    public System.Uri URI { get; set; }

    public string Tn { get; set; }

    public bool HasThisReport { get; set; }

    public string DWBM { get; set; }

    public string Year { get; set; }

    public string Month { get; set; }

    public CODE_BBBMB ReportSetting { get; set; }

    /// <summary>
    /// 报表状态、填报情况、通过校验
    /// </summary>
    public BBTBQK ReportState { get; set; }

    public string LastYear { get; set; }

    public string LastMonth { get; set; }

    public string DataUrl { get; set; }

    public string ZBBMIndex { get; set; }


    /// <summary>
    /// DataTable数据结构 当用户自定义SelectField时 使用该属性获得字段的类型 用于限制用户输入
    /// </summary>
    public List<SSEC.DataBaseDict.Field> DataTableFieldList { get; set; }


    /// <summary>
    /// Oracle Table的数据结构 
    /// </summary>
    public List<SSEC.DataBaseDict.Field> TableFieldList { get; set; }

    /// <summary>
    /// 操作权限
    /// </summary>
    public List<Domain.Permission> Permissions { get; set; }

    public BaseReport(string _tn, string _dwbm, string _year, string _month)
    {
      Tn = _tn;
      DWBM = _dwbm;
      Year = _year;
      Month = _month;
    }

    public bool LoadProduce(string ProcdureName)
    {
      OracleParameter[] parameters ={
            new OracleParameter("v_bbbm",OracleType.VarChar,20),
　　     new OracleParameter("v_dwbm",OracleType.VarChar,20),
　　     new OracleParameter("v_nf",OracleType.Number,4),
            new OracleParameter("v_yf",OracleType.Number,2),
　　      };
      parameters[0].Value = Tn.ToUpper();
      parameters[1].Value = DWBM.ToUpper();
      parameters[2].Value = Year;
      parameters[3].Value = Month;
      try
      {
        OracleDataReader odr = Maticsoft.DBUtility.DbHelperOra.RunProcedure(ProcdureName, parameters);
        odr.Close();
        return true;
      }
      catch
      {
        return false;
      }
    }

    public void InitReport()
    {
      TableFieldList = SSEC.DataBaseDict.DictFactroy.Instance().GetFields(Tn);
      CreateReport();//创建空表
      ReportSetting = CODE_BBBMB.Find(Tn);//报表周期 
      //处理报表时间，当传参为整数时，旬报应如何处理。
      GetPreReportTime();
      //读取报表填报情况
      BBTBQK_CompositeKey pk = new BBTBQK_CompositeKey();
      pk.DWBM = DWBM;
      pk.NF = Year;
      pk.YF = Month;
      pk.BBBM = Tn;
      ReportState = BBTBQK.TryFind(pk);
      //如果没有报表状态 该报表可能是分公司报表 不需要上报
      if (ReportState == null)
      {
        //Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("该表没有报表填报情况！");
        ReportState = new BBTBQK();
        ReportState.BBZT = "未上报";
      }

      //使用配置文件缓存
      string cachekey = "Model.Statistical.BaseReport.InitReport.Config." + Year + "_" + Tn + "." + DWBM;
      Config = (GridConfig)CacheFactroy.Instance().GetCache(cachekey);
      if (Config == null)
      {
        Config = new GridConfig(Tn, Year, DWBM);//加载配置文件       
        CacheFactroy.Instance().SetCache(cachekey, Config);
      }
      //生成报表上报时间
      GetReportTimeStopTime();
    }

    /// <summary>
    /// 报表截止上报时间
    /// </summary>
    public void GetReportTimeStopTime()
    {
      string expression = ReportSetting.YQSBSJ;
      if (!string.IsNullOrEmpty(expression))
      {
        List<string> expList = expression.Split('-').ToList();
        DateTime dt = new DateTime(Year.ToInt32(), Month.ToInt32(), 1);
        dt = dt.AddMonths(Convert.ToInt16(expList[0]));
        dt = dt.AddDays(Convert.ToInt16(expList[1]) - 1);
        dt = dt.AddHours(Convert.ToInt16(expList[2]));
        ReportSetting.ReportStopTime = dt;
      }
    }

    /// <summary>
    /// 处理当前时间和上一次的报表时间
    /// </summary>
    private void GetPreReportTime()
    {
      if (ReportSetting.BBZQ == "半年报")
      {
        if (Month == "6")
        {
          LastMonth = "12";
          LastYear = (Year.ToInt32() - 1).ToString();
        }
        if (Month == "12")
        {
          LastMonth = "6";
          LastYear = Year;
        }
      }

      if (ReportSetting.BBZQ == "季度")
      {
        LastYear = Year;
        if (Month == "3")
        {
          LastMonth = "12";
          LastYear = (Year.ToInt32() - 1).ToString();
        }
        else
        {
          LastMonth = (Month.ToInt32() - 3).ToString();
        }
      }

      if (ReportSetting.BBZQ == "年度")
      {
        LastYear = (Year.ToInt32() - 1).ToString();
        LastMonth = Month;
      }

      if (ReportSetting.BBZQ == "旬度")
      {
        LastYear = Year;

        //整数位
        int zs = Month.ToDecimal().Floor();
        //小数位
        decimal xs = Month.ToDecimal() - zs;
        if (xs == 0M)
        {
          Month = zs.ToString() + ".30";
        }
        else
        {
          if ((xs - 0.1M) == 0)
          {
            if (zs > 1)
              LastMonth = (zs - 1 + 0.30M).ToString();
            else
              LastMonth = (12 + 0.30M).ToString(); LastYear = (Year.ToInt32() - 1).ToString();
          }
          else
          {
            LastMonth = (zs.ToDecimal() + xs.ToDecimal() - 0.1M).ToString();
          }

        }
      }
      if (ReportSetting.BBZQ == "月度")
      {
        LastYear = Year;
        LastMonth = (Month.ToDecimal() - 1).ToString();
        if (Month.ToDecimal() == 0)
        {
          LastMonth = "12";
          LastYear = (Year.ToInt32() - 1).ToString();
        }
        else
          LastYear = Year;
      }
    }

    private void CreateReport()
    {
      if (!IsExist())
      {
        LoadProc("p_create");
      }
    }

    private bool IsExist()
    {
      return Maticsoft.DBUtility.DbHelperOra.Exists("select Count(1) from " + Tn + " where dwbm='" + DWBM + "' and nf='" + Year + "' and yf='" + Month + "'");
    }

    public bool LoadProc(string ProcdureName)
    {
      OracleParameter[] parameters ={
            new OracleParameter("v_bbbm",OracleType.VarChar,20),
　　     new OracleParameter("v_dwbm",OracleType.VarChar,20),
　　     new OracleParameter("v_nf",OracleType.Number,4),
            new OracleParameter("v_yf",OracleType.Number,2),
　　      };
      parameters[0].Value = Tn.ToUpper();
      parameters[1].Value = DWBM.ToUpper();
      parameters[2].Value = Year;
      parameters[3].Value = Month;
      try
      {
        OracleDataReader odr = Maticsoft.DBUtility.DbHelperOra.RunProcedure(ProcdureName, parameters); odr.Close();
        return true;
      }
      catch
      {
        return false;
      }
    }

    public string Get_GridDropDownList_Year()
    {
      string bbzq = ReportSetting.BBZQ;
      StringBuilder sb = new StringBuilder();
      string redirectUrl = this.URI.AbsolutePath + "?tn=" + Tn + "&month=" + Month + "&dwbm=" + DWBM;
      sb.Append("<select id=\"year\" name=\"year\"  panelWidth=\"auto\" panelHeight=auto onchange=\"window.location.href('" + redirectUrl + "&year='+$('#year').val())\">");

      //sb.Append("<select id=\"year\" name=\"year\"  panelWidth=\"auto\" panelHeight=auto onchange=\"ReloadGrid()\">");

      //该报表需要哪些单位填写
      int start =int.Parse(System.Configuration.ConfigurationManager.AppSettings["startyear"].ToString());

      int end = DateTime.Now.Year + 1;
      if (bbzq == "汇编")
      {
        for (int i = start; i <= DateTime.Now.Year + 5; i = i + 5)
        {
          sb.Append("<option value=\"" + i + "\">" + i + "</option>");
        }
      }
      else
      {
        for (int i = start; i <= end; i++)
        {
          sb.Append("<option value=\"" + i + "\">" + i + "</option>");
        }
      }

      sb.Append("</select>");
      sb.Append("<script>$('#year').attr('value','" + Year + "');</script>");
      return sb.ToString();
    }

    public string Get_GridDropDownList_Month()
    {
      string bbzq = ReportSetting.BBZQ;
      StringBuilder sb = new StringBuilder();
      string redirectUrl = this.URI.AbsolutePath + "?tn=" + Tn + "&year=" + Year + "&dwbm=" + DWBM;
      sb.Append("<select id=\"month\" name=\"month\" style=\"width:auto\"  onchange=\"window.location.href('" + redirectUrl + "&month='+$('#month').val())\">");

      //sb.Append("<select id=\"month\" name=\"month\" style=\"width:auto\"  onchange=\"ReloadGrid()\">");
      var q = Select.SelectFactroy.MonthInstance().ListItems;
      foreach (var s in q)
      {
        sb.Append("<option value=\"" + s.Value + "\">" + s.Text + "</option>");
      }
      sb.Append("</select>");
      sb.Append("<script>$('#month').attr('value','" + Month + "');</script>");
      return sb.ToString();
    }

    public string Get_GridDropDownList_Dwbm()
    {
      StringBuilder sb = new StringBuilder();
      //跳转路径
      string redirectUrl = this.URI.AbsolutePath + "?tn=" + Tn + "&year=" + Year + "&month=" + Month;
      sb.Append("<select id=\"dwbm\" name=\"dwbm\" style=\"width:auto\"  onchange=\"window.location.href('" + redirectUrl + "&dwbm='+$('#dwbm').val())\">");

      //sb.Append("<select id=\"dwbm\" name=\"dwbm\" style=\"width:auto\"  onchange=\"ReloadGrid()\">");

      var q = Select.SelectFactroy.DwbmInstance().ListItems;
      foreach (var s in q)
      {
        sb.Append("<option value=\"" + s.Value + "\">" + s.Text + "</option>");
      }
      sb.Append("</select>");
      sb.Append("<script>$('#dwbm').attr('value','" + DWBM + "');</script>");
      return sb.ToString();
    }

    public string Get_GridColumn()
    {
      GridData gd = new GridData(Config.SelectField, Tn, DWBM, Year, Month, Config.OrderBy);
      DataTableFieldList = GridData.GetFileds("" + gd.QuerySQLText + "");

      //使用节点缓存
      string cachekey = "Model.Statistical.BaseReport.Get_GridColumn_" + DWBM + "_" + Year + "_" + Tn;

      string script = (string)Xiaov.SmartWeb.Infrastructure.Cache.CacheFactroy.Instance().GetCache(cachekey);

      if (string.IsNullOrEmpty(script))
      {
        #region 获取表头字符串信息

        ////决定是几层复杂表
        //List<StringBuilder> ListColumnString = new List<StringBuilder>();

        ////将所有配置还原为List
        //List<GridColumnConfig> list = new List<GridColumnConfig>();
        //string[] titles = Config.HeaderTitleName.Split(',');
        //string[] titles_xy = Config.HeaderTitleXY.Split('|');
        //string[] columns = Config.HeaderColumnName.Split(',');
        //string[] columns_xy = Config.HeaderColumnXY.Split('|');

        //for (int i = 0; i < columns.Length; i++)
        //{
        //    GridColumnConfig gcc = new GridColumnConfig();
        //    gcc.Name = columns[i];
        //    string[] t = columns_xy[i].Split(',');
        //    gcc.X = t[0].ToInt32();
        //    gcc.XSpan = t[1].ToInt32();
        //    gcc.Y = t[2].ToInt32();
        //    gcc.YSapn = t[3].ToInt32();
        //    gcc.Title = false;
        //    gcc.Column = true;
        //    list.Add(gcc);
        //}

        //for (int i = 0; i < titles.Length; i++)
        //{
        //    if (titles[i] != "NULL" && titles[i] != "")
        //    {
        //        GridColumnConfig gcc = new GridColumnConfig();
        //        gcc.Name = titles[i];
        //        string[] t = titles_xy[i].Split(',');
        //        gcc.X = t[0].ToInt32();
        //        gcc.XSpan = t[1].ToInt32();
        //        gcc.Y = t[2].ToInt32();
        //        gcc.YSapn = t[3].ToInt32();
        //        gcc.Title = true;
        //        gcc.Column = false;
        //        list.Add(gcc);
        //    }
        //}

        //string YLength = Config.HeaderColumnXY.Split('|').First().Split(',').Last();
        //for (int i = 0; i < YLength.ToInt32(); i++)
        //{
        //    StringBuilder cc = new StringBuilder("");
        //    ListColumnString.Add(cc);
        //}

        //list = list.OrderBy(s => s.X).ToList();
        ////遍历所有放入对应的层
        //foreach (var q in list)
        //{
        //    if (q.Column)
        //    {
        //        ListColumnString[q.Y].Append("{ field: '" + DataTableFieldList[q.X].FieldName + "',width:100, title: '" + q.Name + "', rowspan: " + q.YSapn + ", formatter: function (val, rec) { return unescape(rec." + DataTableFieldList[q.X].FieldName + "); } },");
        //    }
        //    else
        //    {
        //        ListColumnString[q.Y].Append("{ title: '" + q.Name + "',width:100,colspan: " + q.XSpan + ", rowspan: " + q.YSapn + " },");
        //    }
        //}


        //for (int i = 0; i < ListColumnString.Count; i++)
        //{
        //    script += "[" + ListColumnString[i].Remove(ListColumnString[i].ToString().Length - 1, 1) + "],";
        //}

        //script = script.Remove(script.Length - 1, 1);
        #endregion


        #region 获取表头字符串信息 2014-01-13 for chenjun by pengwei

        StringBuilder sb = new StringBuilder();

        List<StringBuilder> ListColumnString = new List<StringBuilder>();
        string[] columns = Config.HeaderColumnName.Split(',');
        string[] columns_xy = Config.HeaderColumnXY.Split('|');
        //有多少行就产生多少个字符串
        for (int i = 0; i < Config.RowCount; i++)
        {
          StringBuilder cc = new StringBuilder("");
          ListColumnString.Add(cc);
        }
        //遍历产生script字符串
        int currentRow = 0;//默认开始为表格的第一行
        int preCellX = -1;//上一个单元格的x值
        for (int i = 0; i < columns.Length; i++)
        {

          GridColumnConfig gcc = new GridColumnConfig();
          gcc.Name = columns[i];
          string[] t = columns_xy[i].Split(',');
          gcc.X = t[0].ToInt32();
          gcc.XSpan = t[1].ToInt32();
          gcc.Y = t[2].ToInt32();
          gcc.YSapn = t[3].ToInt32();
          //Y+YSpan<rowcount 为Title 等于rowcount为Column
          gcc.Column = (gcc.YSapn + gcc.Y) == Config.RowCount;
          gcc.Title = !gcc.Column;
          //赋值                    
          //如果当前的x小于上一个x 说明换一行绘制单元格
          if (gcc.X <= preCellX)
          {
            currentRow++;
          }

          if (!gcc.Column)
          {
            ListColumnString[gcc.Y].Append("{ title: '" + gcc.Name + "',width:100,colspan: " + gcc.XSpan + ", rowspan: " + gcc.YSapn + " },");
          }
          else
          {
            //特殊处理 for chenjun 指标空格的替换方法替换成&nbsp;
            int width = 100; string replacstr = "";
            if (DataTableFieldList[gcc.X].FieldName == "ZBMC")
            {
              width = 200;
              //js空格替换html代码
              //replacstr = ".replace(/[ ]/g, \"&nbsp;\")"; 
            }
            ListColumnString[currentRow].Append("{ field: '" + DataTableFieldList[gcc.X].FieldName + "',width:" + width + ", title: '" + gcc.Name + "', rowspan: " + gcc.YSapn + ", formatter: function (val, rec) { return unescape(rec." + DataTableFieldList[gcc.X].FieldName + ")" + replacstr + "; } },");
          }
          preCellX = gcc.X;
        }

        for (int i = 0; i < Config.RowCount; i++)
        {
          script += "[" + ListColumnString[i].Remove(ListColumnString[i].ToString().Length - 1, 1) + "],";
        }
        script = script.Remove(script.Length - 1, 1);
        #endregion

        Xiaov.SmartWeb.Infrastructure.Cache.CacheFactroy.Instance().SetCache(cachekey, script);
      }

      //Hack:获取数据的同时生成指标编码的行索引..暂时写在这里 待结构调整
      cachekey = "Model.Statistical.BaseReport.Get_GridColumn_" + DWBM + "_" + Year + "_" + Tn + "_ZBBMIndex";
      ZBBMIndex = (string)Xiaov.SmartWeb.Infrastructure.Cache.CacheFactroy.Instance().GetCache(cachekey);
      if (string.IsNullOrEmpty(ZBBMIndex))
      {
        int k = 0;
        foreach (System.Data.DataRow dr in gd.Data.Tables[0].Rows)
        {
          ZBBMIndex += "{name:'" + dr["ZBBM"] + "',index:" + k.ToString() + "},";
          k++;
        }
        ZBBMIndex = ZBBMIndex.Remove(ZBBMIndex.Length - 1);
        Xiaov.SmartWeb.Infrastructure.Cache.CacheFactroy.Instance().SetCache(cachekey, ZBBMIndex);
      }

      return script;

    }

    public string Get_GridLockRow()
    {
      return Config.NotAllowEditRow;
    }

    public string Get_GridLockColumn()
    {
      return Config.NotAllowEditColumn;
    }

    public string Get_GridLockCell()
    {
      return Config.NotAllowEditCells;
    }

    public string Get_ColWidth()
    {
      return Config.ColumnWidth;
    }

    public string Get_GridHC()
    {
      return Config.NameHierarchy;
    }

    public string Get_GridTitle()
    {
      return Config.Title;
    }

    public string Get_GridDataUrl()
    {
      return "/PluginSrc/StatisticalSystem/CommData.aspx?tn=" + Tn + "&orderby=" + Config.OrderBy + "&year=" + Year + "&month=" + Month + "&dwbm=" + DWBM + "";
    }

    public string Get_GridHiddenColumn()
    {
      return Config.HiddenColumn;
    }

    public string Get_GridHiddenRow()
    {
      return Config.HiddenRow;
    }

    public string Html(string path)
    {
      string Regkey = @"#\b\w+\b#";
      string html = Xiaov.SmartWeb.Infrastructure.Common.General.ReadFileText(System.Web.HttpContext.Current.Server.MapPath(path));
      Regex regex = new Regex(Regkey, RegexOptions.IgnoreCase);
      MatchCollection matchs = regex.Matches(html);
      foreach (Match match in matchs)
      {
        string tag = match.Groups[0].Value;
        string tagName = tag.Remove(0, 1);
        tagName = tagName.Remove(tagName.Length - 1, 1);
        ITag itag;
        itag = (ITag)Assembly.Load("Xiaov.SmartWeb.Model").CreateInstance("Xiaov.SmartWeb.Model.Statistical.Tags." + tagName);
        string replacetxt = itag.Value(this);
        html = html.Replace(tag, replacetxt);
      }
      return html;
    }

    /// <summary>
    /// 重置参数值
    /// </summary>
    /// <param name="dw">报表单位</param>
    /// <param name="tn">tablename</param>
    /// <param name="nf">年份</param>
    /// <param name="yf">月份</param>
    /// <param name="userDeptId">当前用户所在部门：用于确定管理范围</param>
    public void ReSetParmas(string dw, string tn, string nf, string yf, string userDeptId)
    {
      try
      {
        if (!string.IsNullOrEmpty(tn))
        {
          string bbzq = CODE_BBBMB.TryFind(tn).BBZQ;
          SelectFactroy.InitFactroy(bbzq);
          SelectFactroy.MonthInstance().DataBind(dw, tn, nf, yf);
          SelectFactroy.DwbmInstance().DataBind(userDeptId, tn, nf, yf);
          //判断没有月份
          var q = SelectFactroy.MonthInstance().ListItems;
          bool f = (q.Where(s => s.Value == Month).Count() > 0);
          if (!f)
          {
            Month = SelectFactroy.MonthInstance().DefaultValue;
          }
          //判断没有单位
          q = SelectFactroy.DwbmInstance().ListItems;
          f = (q.Where(s => s.Value == dw).Count() > 0);
          if (!f)
          {
            DWBM = SelectFactroy.DwbmInstance().DefaultValue;
          }
          //将年份、月份、单位、发送给客户端
          HttpCookie cookies = new HttpCookie("UserSelectInfo");
          cookies.Values["DW"] = DWBM;
          cookies.Values["NF"] = Year;
          cookies.Values["YF"] = Month;

          cookies.Expires = DateTime.MaxValue;
          HttpContext.Current.Response.Cookies.Add(cookies);
        }
      }
      catch
      {
        Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("报表编码表中没有" + tn + "的描述");
      }
    }
  }
}
